import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class BannerView extends StatefulWidget {
  final List<Widget> children;///banner
  final Duration switchDuration; ///切换时间

  BannerView(this.children, this.switchDuration);

  @override
  _BannerViewState createState() => _BannerViewState();
}

class _BannerViewState extends State<BannerView> with SingleTickerProviderStateMixin{
  int _currentIndex = 0;
  Timer _timer;
  PageController _pageController;
  TabController _tabController;
  List<Widget> children = [];
  static const Duration animationDuration = const Duration(milliseconds: 500);

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    var _children = widget.children;
    children.addAll(_children);
    if(children.length > 1){
      _currentIndex = 1;
      children.insert(0, _children[_children.length - 1]);
      children.add(_children[0]);
    }
    _pageController = PageController(initialPage: _currentIndex);
    _tabController = TabController(length: _children.length,vsync:this);
    _nextBanner();
  }
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _tabController.dispose();
    _pageController.dispose();
    _timer?.cancel();
  }
  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        PageView.builder(
          itemCount: children.length,
          controller: _pageController,
          onPageChanged: _onPageChanged,
          itemBuilder: (context,index){
            return Listener(
              child: children[index],
              onPointerDown: (_){_timer?.cancel();},
              onPointerUp: (_){_nextBanner();},
            );
          },
        ),
        Align(
          alignment: Alignment.bottomRight,
          child: TabPageSelector(
            color:Colors.white,
            selectedColor: Colors.grey,
            controller: _tabController,
          ),
        )
      ],
    );
  }

  void _nextBanner(){
    if(!(_timer?.isActive??false) && children.length > 1){
      _timer = Timer.periodic(widget.switchDuration, _doChangeIndex);
    }
  }
  void _doChangeIndex(Timer timer){
    if(children.length > 1){
      _currentIndex = _computeIndex(_currentIndex++);
      _pageController.animateToPage(_currentIndex, duration: animationDuration, curve: Curves.easeInOut);
    }
  }
  int _computeIndex(int index){
    /// 在跳到最后一页的时候，不跳到最后一页，跳到第1页
    /// todo 效果是往回跳？
    return index == children.length -1?1:_currentIndex;
  }
  void _onPageChanged(int index){
    if(children.length <= 1){
      return;
    }
    if(index == 0){
      _tabController.animateTo(_tabController.length -1);
    }else if(index == children.length -1){
      _tabController.animateTo(0);
    }else{
      _tabController.animateTo(index - 1);
    }
  }
}
